package org.ielse.frame.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ViewUtil {
	public static int getViewMeasuredWidth(View view) {
		int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
		int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
		view.measure(width, expandSpec);
		return view.getMeasuredWidth();
	}

	public static void changeFontsStyle(Activity act, Typeface tf) {
		changeFontsStyle(getContentView(act), act, tf);
	}

	public static void changeFontsStyle(View root, Context context, Typeface typeface) {
		if (context == null) {
			Log.e("ViewUtil", "changeFontsStyle() empty context");
			return;
		}

		if (root != null) {
			if (root instanceof ViewGroup) {
				for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
					View v = ((ViewGroup) root).getChildAt(i);
					if (v instanceof TextView) {
						((TextView) v).setTypeface(typeface);
					}
					else if (v instanceof Button) {
						((Button) v).setTypeface(typeface);
					}
					else if (v instanceof EditText) {
						((EditText) v).setTypeface(typeface);
					}
					else if (v instanceof ViewGroup) {
						changeFontsStyle((ViewGroup) v, context, typeface);
					}
				}
			}
			else {
				if (root instanceof TextView) {
					((TextView) root).setTypeface(typeface);
				}
				else if (root instanceof Button) {
					((Button) root).setTypeface(typeface);
				}
				else if (root instanceof EditText) {
					((EditText) root).setTypeface(typeface);
				}
			}
		}
	}

	private static ViewGroup getContentView(Activity act) {
		ViewGroup systemContent = (ViewGroup) act.getWindow().getDecorView().findViewById(android.R.id.content);
		ViewGroup content = null;
		if (systemContent.getChildCount() > 0 && systemContent.getChildAt(0) instanceof ViewGroup) {
			content = (ViewGroup) systemContent.getChildAt(0);
		}
		return content;
	}

}
